<?php

namespace App\Http\Controllers\Entity\Asset\Video;

use App\Admin\Extensions\Tools\GridView;
use App\Classes\Injection\VassetiInjection;
use App\Classes\Publish\Publication;
use App\Http\Controllers\Controller;
use App\Http\Requests\Entity\Asset\Video\VassetiRequest;
use App\Jobs\Import\ImportVassetiJob;
use App\Jobs\Injection\VassetiInjectionJob;
use App\Jobs\Publish\VassetiJob;
use App\Models\Common\CatData\Video\Vcat;
use App\Models\Common\EntityData\Channel\Cp;
use App\Models\Common\EntityData\Channel\Sp;
use App\Models\Common\EntityData\Video\Actor;
use App\Models\Common\EntityData\Video\Director;
use App\Models\Common\Enumdata\Enumop\Video\Varea;
use App\Models\Common\Enumdata\Enumop\Video\Vlang;
use App\Models\Common\Enumdata\Enumop\Video\Vyear;
use App\Models\Common\TagData\Video\Vcattag;
use App\Models\Entity\Asset\Video\Media\Vifile;
use App\Models\Entity\Asset\Video\Media\Vposteri;
use App\Models\Entity\Asset\Video\Vasseti;
use App\Models\Entity\Asset\Video\VassetiVcattag;
use App\Models\Entity\Asset\Video\Vseriali;
use App\Models\Entity\content_audit\content_audit;
use App\Models\Import\BatchImportVassetiHistory;
use App\Models\Injection\InjectVassetiHistory;
use App\Repositories\Entity\Asset\Video\VassetiRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Excel;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Response;
use Validator;

class VassetiController extends Controller
{
    use ModelForm;

    /** @var  VassetiRepository */
    private $vassetiRepository;

    protected $model;

    public function __construct(VassetiRepository $vassetiRepo)
    {
        $this->model             = new Vasseti;
        $this->vassetiRepository = $vassetiRepo;
    }

    /**
     * Display a listing of the Vasseti.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        Admin::script('injectVasseti();');
        return Admin::content(function (Content $content) use ($request) {
            $content->header('视频总集');
            switch ($request->get('view')){
                case 'editor':
                {
                    $content->description('编辑审核申请');
                    $content->body($this->editor_grid($request));
                    break;
                }
                case 'online':
                {
                    $content->description('上线申请');
                    $content->body($this->online_grid($request));
                    break;
                }
                case 'publish':
                {
                    $content->description('发布申请');
                    $content->body($this->publish_grid($request));
                    break;
                }
                case 'offline':
                {
                    $content->description('下线申请');
                    $content->body($this->offline_grid($request));
                    break;
                }
                default:
                    $content->description(__('entity.asset.video.vassetis.index_description'));
                    $content->body($this->grid($request));
                    $content->row(view('entity.tag.addContentTagModal'));
                    break;
            }

        });
    }

    /**
     * Show the form for creating a new Vasseti.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.asset.video.vassetis.create_header'));
            $content->description(__('entity.asset.video.vassetis.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Vasseti in storage.
     *
     * @param VassetiRequest $request
     *
     * @return Response
     */
    public function store(VassetiRequest $request)
    {
        $input   = $request->all();
        $vasseti = $this->vassetiRepository->create($input);
        if ($vasseti) {
            // 手动添加-中间表
            if (is_array($request->get('sps'))) {
                $vasseti->sps()->sync(array_filter($request->get('sps')));
            }
            if (is_array($request->get('cps'))) {
                $vasseti->cps()->sync(array_filter($request->get('cps')));
            }
            if (is_array($request->get('directors'))) {
                $vasseti->directors()->sync(array_filter($request->get('directors')));
            }
            if (is_array($request->get('actors'))) {
                $vasseti->actors()->sync(array_filter($request->get('actors')));
            }
            if (is_array($request->get('vifiles'))) {
                $vasseti->vifiles()->sync(array_filter($request->get('vifiles')));
            }
            if (is_array($request->get('vposteris'))) {
                $vasseti->vposteris()->sync(array_filter($request->get('vposteris')));
            }
            if (is_array($request->get('vyears'))) {
                $vasseti->vyears()->sync(array_filter($request->get('vyears')));
            }
            if (is_array($request->get('vlangs'))) {
                $vasseti->vlangs()->sync(array_filter($request->get('vlangs')));
            }
            if (is_array($request->get('vareas'))) {
                $vasseti->vareas()->sync(array_filter($request->get('vareas')));
            }
        }

        Flash::success(__('entity.asset.video.vassetis.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.asset.video.vassetis.index'));
    }

    /**
     * Display the specified Vasseti.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $vasseti = $this->vassetiRepository->findWithoutFail($id);

        if (empty($vasseti)) {
            Flash::error(__('entity.asset.video.vassetis.not_found'));

            return redirect(route('entity.asset.video.vassetis.index'));
        }

        return view('entity.asset.video.vassetis.show')->with('vasseti', $vasseti);

    }

    /**
     * Show the form for editing the specified Vasseti.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('entity.asset.video.vassetis.edit_header'));
            $content->description(__('entity.asset.video.vassetis.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Vasseti in storage.
     *
     * @param  int              $id
     * @param VassetiRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $sValidators = [
            'vasseti_no'  => 'required|max:100|unique:vassetis,vasseti_no,' . $id,
            'name'        => 'required|max:100',
            'title'       => 'max:100',
            'subtitle'    => 'max:100',
            'score'       => 'numeric',
            // 'season'      => 'numeric',
            'episode'     => 'numeric',
            'serials'     => 'numeric',
            'vcat_id'     => 'required|max:10',
            'short_desc'  => 'required',
            'charge_type' => 'required',
            'listorder'   => 'required|numeric',
        ];
        $validators = [];

        $input = $request->all();

        // 判断是否行内编辑,只有下线的可以编辑
        $status = Vasseti::where(['online_status' => 0, 'id' => $id])->first();
        if ($status) {
            $input = $this->handleEditable($input);
        }

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }

        // 定义校验, 没有移到request
        $validator = Validator::make($input, $validators, [
            // 'required' => ':attribute 不能为空',
        ], [
            'vasseti_no' => '剧集编号',
            'name'       => '名称',
            'title'      => '标题',
            'subtitle'   => '副标题',
            'score'      => '评分',
            // 'season'     => '第几季',
            'episode'    => '集数',
            'serials'    => '集数',
            'vcat_id'    => '分类',
            'short_desc' => '描述',
            'listorder'  => '排序',
        ]
        );

        // 校验
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        // 排序
        if ($this->handleOrderable($id, $input)) {
            return response([
                'status'  => true,
                'message' => trans('admin::lang.update_succeeded'),
            ]);
        }

        $vasseti = $this->vassetiRepository->findWithoutFail($id);
        if (empty($vasseti)) {
            Flash::error(__('entity.asset.video.vassetis.not_found'));

            return redirect(route('entity.asset.video.vassetis.index'));
        }
        $vasseti = $this->vassetiRepository->update($input, $id);

        if ($vasseti) {
            // 手动添加-中间表
            if (is_array($request->get('sps'))) {
                $vasseti->sps()->sync(array_filter($request->get('sps')));
            }
            if (is_array($request->get('cps'))) {
                $vasseti->cps()->sync(array_filter($request->get('cps')));
            }
            if (is_array($request->get('directors'))) {
                $vasseti->directors()->sync(array_filter($request->get('directors')));
            }
            if (is_array($request->get('actors'))) {
                $vasseti->actors()->sync(array_filter($request->get('actors')));
            }
            if (is_array($request->get('vifiles'))) {
                $vasseti->vifiles()->sync(array_filter($request->get('vifiles')));
            }
            if (is_array($request->get('vposteris'))) {
                $vasseti->vposteris()->sync(array_filter($request->get('vposteris')));
            }
            if (is_array($request->get('vyears'))) {
                $vasseti->vyears()->sync(array_filter($request->get('vyears')));
            }
            if (is_array($request->get('vlangs'))) {
                $vasseti->vlangs()->sync(array_filter($request->get('vlangs')));
            }
            if (is_array($request->get('vareas'))) {
                $vasseti->vareas()->sync(array_filter($request->get('vareas')));
            }
            if (is_array($request->get('vcattags'))) {
                $vasseti->vcattags()->sync(array_filter($request->get('vcattags')));
            }
        }

        Flash::success(__('entity.asset.video.vassetis.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.asset.video.vassetis.index'));
    }

    /**
     * Remove the specified Vasseti from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        } else {
            // 只有下线且下线发布或上线未发布的才能删除
            $vasseti = Vasseti::where('id', $id)->where(['publish_down_status' => 1])->orWhere(['online_status' => 1, 'publish_status' => 0])->first();
            if (empty($vasseti)) {
                return response()->json(['message' => '只有状态为下线且已下线发布才可以删除', 'status' => false]);
            }
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            // 只有下线且下线发布的才能删除
            $id = Vasseti::where(['online_status' => 0, 'publish_down_status' => 1])->whereIn('id', $id)->pluck('id')->toArray();
            if ($flag = $this->vassetiRepository->batchDelete('id', $id)) {
                $vasseti->sps()->detach();

                $vasseti->cps()->detach();

                $vasseti->directors()->detach();

                $vasseti->actors()->detach();
                $vasseti->vifiles()->detach();

                $vasseti->vposteris()->detach();

                $vasseti->vyears()->detach();

                $vasseti->vlangs()->detach();

                $vasseti->vareas()->detach();
                return response()->json(['message' => __('entity.asset.video.vassetis.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => '只有状态为下线发布的才可以删除', 'status' => $flag]);
            }
        }

        $vasseti = $this->vassetiRepository->findWithoutFail($id);

        if (empty($vasseti)) {
            Flash::error(__('entity.asset.video.vassetis.not_found'));

            return redirect(route('entity.asset.video.vassetis.index'));
        }

        if ($flag = $this->vassetiRepository->delete($id)) {

            $vasseti->sps()->detach();

            $vasseti->cps()->detach();

            $vasseti->directors()->detach();

            $vasseti->actors()->detach();
            $vasseti->vifiles()->detach();

            $vasseti->vposteris()->detach();

            $vasseti->vyears()->detach();

            $vasseti->vlangs()->detach();

            $vasseti->vareas()->detach();
            return response()->json(['message' => __('entity.asset.video.vassetis.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }
    // 剧集详情
    public function vassetiDetails($id)
    {

        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('剧集详情'));

            // if (Request::get('view') !== 'table') {
            //     $grid->view('admin.grid.card');
            // }

            // 剧集详情
            $data = $this->assetDetailsData($id);
            $content->row(view('entity.asset.video.vasseti.details', $data));

            // 剧集详情
            // $content->row($this->assetDetailsBox($id));

            // 分集数据
            $content->row($this->vassetiTab($id));
            // $content->body($this->vassetiGrid($id));
        });
    }

    // 剧集详情的数据
    public function assetDetailsData($id)
    {
        $vassetiDetails = Vasseti::where('id', '=', $id)->with('sps', 'cps', 'directors', 'actors', 'vlangs', 'vareas', 'vyears', 'vcattags')->first();

        // 内容商
        $cps = '';
        if ($cps = $vassetiDetails->cps) {
            $cps = $vassetiDetails->cps->pluck('name')->implode(',');
        }
        // 服务商
        $sps = '';
        if ($sps = $vassetiDetails->sps) {
            $sps = $vassetiDetails->sps->pluck('name')->implode(',');
        }
        // 演员
        $actors = '';
        if ($actors = $vassetiDetails->actors) {
            $actors = $vassetiDetails->actors->pluck('name')->implode(',');
        }
        // 导演
        $directors = '';
        if ($directors = $vassetiDetails->directors) {
            $directors = $vassetiDetails->directors->pluck('name')->implode(',');
        }
        // 语言
        $vlangs = '';
        if ($vlangs = $vassetiDetails->vlangs) {
            $vlangs = $vassetiDetails->vlangs->pluck('name')->implode(',');
        }
        // 年代
        $vyears = '';
        if ($vyears = $vassetiDetails->vyears) {
            $vyears = $vassetiDetails->vyears->pluck('name')->implode(',');
        }
        // 地区
        $vareas = '';
        if ($vareas = $vassetiDetails->vareas) {
            $vareas = $vassetiDetails->vareas->pluck('name')->implode(',');
        }
        // 归类
        $vcat = '';
        if ($vcat = $vassetiDetails->vcat) {
            $vcat = $vassetiDetails->vcat->name;
        }
        // 分类
        $vcattags = '';
        if ($vcattags = $vassetiDetails->vcattags) {
            $vcattags = $vassetiDetails->vcattags->pluck('name')->implode(',');
        }

        $data['name']       = $vassetiDetails->name;
        $data['vasseti_no'] = $vassetiDetails->vasseti_no;
        $data['title']      = $vassetiDetails->title;
        $data['subtitle']   = $vassetiDetails->subtitle;
        $data['score']      = $vassetiDetails->score;
        $data['episode']    = $vassetiDetails->episode;
        $data['season']     = $vassetiDetails->season;
        $data['tags']       = $vcattags;
        $data['vcat']       = $vcat;
        $data['short_desc'] = $vassetiDetails->short_desc;
        $data['long_desc']  = $vassetiDetails->long_desc;
        $data['directors']  = $directors;
        $data['actors']     = $actors;
        $data['cps']        = $cps;
        $data['sps']        = $sps;
        $data['vlangs']     = $vlangs;
        $data['vyears']     = $vyears;
        $data['vareas']     = $vareas;
        $data['firstdate']  = date('Y-m-d', strtotime($vassetiDetails->firstdate)); // $vassetiDetails->firstdate
        $data['online_at']  = date('Y-m-d', strtotime($vassetiDetails->online_at)); // $vassetiDetails->online_at
        $data['offline_at'] = date('Y-m-d', strtotime($vassetiDetails->offline_at)); // $vassetiDetails->offline_at;

        return $data;
    }

    // 剧集tab
    public function vassetiTab($id)
    {
        $tab = new Tab();
        // if ($vasseti = Vasseti::has('vserialis')->find($id)) {
        // $vasseti = Vasseti::where(['id' => $id, 'vasseti_type' => 1])->first();
        if (Vasseti::where(['id' => $id, 'vasseti_type' => 1])->first() || Vasseti::has('vserialis')->find($id)) {
            $tab->add('图片信息', $this->vposteriGrid($id));
            $tab->add('分集信息', $this->vassetiGrid($id));
        } else {
            $tab->add('图片信息', $this->vposteriGrid($id));
            $tab->add('文件信息', $this->vifileGrid($id));
        }
        return $tab;
    }

    // 文件信息
    public function vifileGrid($id)
    {
        return Admin::grid(Vifile::class, function (Grid $grid) use ($id) {

            // 如果媒资已经上线且发布,则不让新增、编辑、删除操作
            $data = Vasseti::where('id', '=', $id)->select('online_status', 'publish_status')->first();

            if ($data && $data->online_status == 1 && $data->publish_status == 1) {
                // 禁用行操作列
                $grid->disableActions();
                // 禁用创建按钮
                $grid->disableCreation();
            }

            // 文件数据
            $vifiles = Vasseti::find($id)->vifiles->toArray();
            $grid->model()->whereIn('id', array_column($vifiles, 'id'));
            $grid->column('id', 'ID')->sortable();
            $grid->column('sp.name', '服务商')->sortable();
            $grid->column('resolution.name', '清晰度')->sortable();
            $grid->column('vfileext.name', '文件扩展名')->sortable();
            $grid->column('title', '标题')->editable();
            $grid->column('subtitle', '副标题')->sortable();
            $grid->column('name', '名称')->editable();
            $grid->column('alias_name', '别名')->editable();
            $grid->column('path', '文件路径')->sortable();
            $grid->column('size', '文件大小(M)')->sortable();
            $grid->column('md5', '文件MD5')->sortable();
            $grid->column('duration', '时长')->sortable();
            $grid->column('href', '下载路径')->sortable();
            $grid->column('type', '文件类型')->display(function ($val) {
                switch ($val) {
                    case 1:
                        return '正片';
                        break;
                    case 2:
                        return '片花';
                        break;
                    case 3:
                        return '预告';
                        break;
                    default:
                        return '其他';
                        break;
                }
            });
            $grid->column('short_desc', '简述')->editable();
            $grid->column('listorder', '排序')->sortable()->editable();

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    $batch->disableDelete();
                });
            });

            // 修改新建, 编辑, 删除按钮的路径
            // $grid->resource(route('entity.asset.video.media.vifiles.index'));
            $grid->resource(route('entity.asset.video.media.vifiles.vasseti.index', ['vasseti_id' => $id]));

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                $filter->disableIdFilter();

            });
        }, 'vifile');
    }

    // 图片信息
    public function vposteriGrid($id)
    {
        return Admin::grid(Vposteri::class, function (Grid $grid) use ($id) {

            $uploadConfig = config('custom.base.upload.vasseti');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $uploadHosts  = config('custom.base.host');
            $host         = $uploadHosts[$driver];

            // 图片数据
            $vposteris = Vasseti::find($id)->vposteris->toArray();
            $grid->model()->whereIn('id', array_column($vposteris, 'id'));
            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '名称')->editable();
            $grid->column('title', '显示标题')->editable();
            $grid->column('subtitle', '显示副标题')->sortable();
            $grid->column('vimgtag.name', '图片类型')->sortable();
            $grid->column('imgtpl.name', '图像规格')->sortable();
            $grid->column('href', '海报链接')->sortable();
            $grid->column('listorder', '排序')->sortable()->editable();

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    $batch->disableDelete();
                });
            });

            // 如果媒资已经上线且发布,则不让新增、编辑、删除操作
            $data = Vasseti::where('id', '=', $id)->select('online_status', 'publish_status')->first();

            if ($data && $data->online_status == 1 && $data->publish_status == 1) {
                // 禁用行操作列
                $grid->disableActions();
                // 禁用创建按钮
                $grid->disableCreation();

                $flag = false;

            } else {

                $flag = true;

            }

            // 修改新建, 编辑, 删除按钮的路径
            // $grid->resource(route('entity.asset.video.media.vposteris.index'));
            $grid->resource(route('entity.asset.video.media.vposteris.vasseti.index', ['vasseti_id' => $id]));

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                $filter->disableIdFilter();
            });

            $grid->tools(function ($tools) {
                $tools->append(new GridView());
            });

            if (\Illuminate\Support\Facades\Request::get('view') !== 'table') {
                $grid->setView('admin.grid.card', ['image_column' => 'href', 'text_column' => 'title', 'server' => $host, 'flag' => $flag]);
            }
        }, 'vposteri');
    }

    // 分集信息
    public function vassetiGrid($id)
    {
        return Admin::grid(Vseriali::class, function (Grid $grid) use ($id) {

            // 如果媒资已经上线且发布,则不让新增、编辑、删除操作
            $data = Vasseti::where('id', '=', $id)->select('online_status', 'publish_status')->first();

            if ($data && $data->online_status == 1 && $data->publish_status == 1) {
                // 禁用行操作列
                $grid->disableActions();
                // 禁用创建按钮
                $grid->disableCreation();
            }

            // 分集数据
            $grid->model()->where('vasseti_id', $id);
            $grid->column('id', 'ID')->sortable();
            $grid->column('vseriali_no', '分集编号');
            $grid->column('name', '分集名称')->editable();
            $grid->column('title', '标题')->editable();
            $grid->column('episode', '第几集')->editable();
            $grid->column('score', '分集评分')->editable();
            $grid->column('firstdate', '首播日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            $grid->column('short_desc', '简介')->editable();
            $grid->column('listorder', '排序')->sortable()->editable();
            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    $batch->disableDelete();
                });
            });

            $grid->actions(function ($actions) {
                // 编辑按钮
                // $actions->disableEdit();
                // 删除按钮
                // $actions->disableDelete();
            });

            // 修改新建, 编辑, 删除按钮的路径
            // $grid->resource(route('entity.asset.video.vserialis.index'));
            $grid->resource(route('entity.asset.video.vserialis.vasseti.index', ['vasseti_id' => $id]));

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                $filter->disableIdFilter();
            });
        }, 'vasseti');

    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Vasseti::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('vasseti_no', '编号')->help('必填');
            $form->text('name', '名称')->help('必填');
            $form->text('title', '标题');
            $form->text('subtitle', '副标题');
            $form->select('vasseti_type', '剧集类型')->options(array(0 => '单集', 1 => '分集总集'))->default(0);
            $form->number('score', '评分');
            $form->number('season', '第几季');
            $form->number('serials', '总集数');
            $form->number('upto', '更新到');
            $vcats = Vcat::pluck('name', 'id')->toArray();
            $form->select('vcat_id', '归类')->options(['' => '选择'] + $vcats)->load('vcattags', route('common.cat_data.video.vcats.vcattag_or_empty'), 'id', 'name')->help('必填');
            $vcattags = Vcattag::pluck('name', 'id')->toArray();
            // $form->multipleSelect('vcattags', '分类')->options($vcattags);
            $form->multipleSelect('vcattags', '分类')->options(['' => '选择'] + $vcattags);
            $vyears = Vyear::pluck('name', 'id');
            $form->multipleSelect('vyears', '年代')->options($vyears);
            $vareas = Varea::pluck('name', 'id');
            $form->multipleSelect('vareas', '地区')->options($vareas);
            $vlangs = Vlang::pluck('name', 'id');
            $form->multipleSelect('vlangs', '语言')->options($vlangs);
            $vifiles = Vifile::pluck('name', 'id');
            $form->multipleSelect('vifiles', '资源文件')->options($vifiles);
            $vposteris = Vposteri::pluck('name', 'id');
            $form->multipleSelect('vposteris', '图片')->options($vposteris);
            // 新增分集
            // $form->hasMany('vserialis', '分集', function (Form\NestedForm $form) {
            //     $vserialis = Vseriali::pluck('name', 'id')->toArray();
            //     // 分集名称
            //     $form->select('vserialis', '名称')->options($vserialis);
            // });
            $form->date('firstdate', '首播日期')->default(date('Y-m-d',time()));
            $form->date('online_at', '上线日期')->default(date('Y-m-d',time()));
            $form->date('offline_at', '下线日期')->default(date('Y-m-d',time()));
            $form->textarea('short_desc', '简介')->help('必填');
            $form->textarea('long_desc', '详情');
            $sps = Sp::pluck('name', 'id');
            $form->multipleSelect('sps', '服务商(SP)')->options($sps);
            $cps = Cp::pluck('name', 'id');
            $form->multipleSelect('cps', '内容商(CP)')->options($cps);
            $directors = Director::pluck('name', 'id');
            $form->multipleSelect('directors', '导演')->options($directors);
            $actors = Actor::pluck('name', 'id');
            $form->multipleSelect('actors', '演员')->options($actors);
            $form->select('charge_type', '收费类型')->options(array(
                0 => '免费',
                1 => '收费',
            ));
            $form->number('listorder', '排序');

            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid(Request $request)
    {
        return Admin::grid(Vasseti::class, function (Grid $grid) use ($request) {

            // 状态过滤
             //Publication::statusFilter($request->input('status'), $request->input('published'), $grid);
            $grid->model()->spid();
            // 表格中的按钮
            $grid->actions(function ($actions) {
                // 表格中的按钮, 新增剧集详情
                // $actions->disableDelete();
                // $actions->disableEdit();
                // $publish_status      = $actions->row->publish_status;
                // $publish_down_status = $actions->row->publish_down_status;
                // $online_status       = $actions->row->online_status;
                $id                  = $actions->getKey();
                // 媒资编辑按钮
                // if ($publish_down_status === 1 && $online_status === 0 && Admin::user()->can('entity.asset.video.vassetis.vasseti_details')) {
                $url = route('entity.asset.video.vassetis.vasseti_details', ['vasseti_id' => $id]);
                $actions->prepend('<a href ="' . $url . '" title="剧集详情"><i class="fa fa-list"></i></a>');
                // }

                // // 上线按钮
                // if ($publish_down_status === 1 && $online_status === 0 && Admin::user()->can('entity.asset.video.vassetis.up')) {
                //     $url      = route('entity.asset.video.vassetis.up');
                //     $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'up',_token: LA.token})";
                //     $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线"><i class="fa fa-arrow-up"></i></a>');
                // }
                // // 下线按钮
                // if ($online_status === 1 && Admin::user()->can('entity.asset.video.vassetis.down')) {
                //     $url      = route('entity.asset.video.vassetis.down');
                //     $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'down',_token: LA.token})";
                //     $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="下线"><i class="fa fa-arrow-down"></i></a>');
                // }
                // // 上线发布按钮
                // if ($online_status === 1 && $publish_status === 0  && Admin::user()->can('entity.asset.video.vassetis.publish_one')) {
                //     $url      = route('entity.asset.video.vassetis.publish_one');
                //     $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'publish',_token: LA.token})";
                //     $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线发布"><i class="fa fa-cloud-upload"></i></a>');
                // }
                // // 下线发布按钮
                // if ($online_status === 0 && $publish_down_status === 0 && Admin::user()->can('entity.asset.video.vassetis.publish_down_one')) {
                //     $url      = route('entity.asset.video.vassetis.publish_down_one');
                //     $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'publishDown',_token: LA.token})";
                //     $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="下线发布"><i class="fa fa-cloud-download"></i></a>');
                // }
                //打标签
                $url = route('entity.tag.selectTag', ['tag_content_id' => $id,'tag_content_type'=>'vasseti']);
                $actions->append('<a href="'.$url.'" data-toggle="modal"  data-target="#add-content-tag-modal" title="打标签"><i class="fa fa-paper-plane"></i></a>');

                //导入栏目
                $url = route('application.column_assets.selectColumn', ['content_id' => $id,'content_type'=>'1']);
                $actions->append('<a href="'.$url.'" data-toggle="modal"  data-target="#add-content-tag-modal" title="导入栏目"><i class="fa fa-download"></i></a>');

                // 编辑按钮
                if (Admin::user()->cannot('entity.asset.video.vassetis.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('entity.asset.video.vassetis.destroy')) {
                    $actions->disableDelete();
                }

            });

            //添加按钮
            if (Admin::user()->cannot('entity.asset.video.vassetis.create')) {
                $grid->disableCreation();
            }

            //导出按钮
            if (Admin::user()->cannot('entity.asset.video.vassetis.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {

                //$url2 = route('entity.asset.video.vassetis.progress');
                // // 下线发布功能
                // if (Admin::user()->can('entity.asset.video.vassetis.publish_down')) {
                //     $url      = route('entity.asset.video.vassetis.publish_down');
                //     $function = "upAndDownByAll('$url', '$url2', 'get')";
                //     $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-info pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-download"></i>下线发布</a>');
                // }
                // // 上线发布功能
                // if (Admin::user()->can('entity.asset.video.vassetis.publish')) {
                //     $url      = route('entity.asset.video.vassetis.publish');
                //     $function = "upAndDownByAll('$url', '$url2', 'get')";
                //     $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-info pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-upload"></i>上线发布</a>');
                // }
                // // 全部下线功能
                // if (Admin::user()->can('entity.asset.video.vassetis.all_down')) {
                //     $url      = route('entity.asset.video.vassetis.all_down');
                //     $function = "upAndDownByAll('$url', '$url2', 'get')";
                //     $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-danger pull-right" style="margin-right: 10px"> <i class="fa fa-arrow-down"></i>全部下线</a>');
                // }
                // // 全部上线功能
                // if (Admin::user()->can('entity.asset.video.vassetis.all_up')) {
                //     $url      = route('entity.asset.video.vassetis.all_up');
                //     $function = "upAndDownByAll('$url', '$url2', 'get')";
                //     $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-success pull-right" style="margin-right: 10px"> <i class="fa fa-arrow-up"></i>全部上线</a>');
                // }
                // 过滤按钮
                //$tools->append(new \App\Admin\Extensions\Tools\Vasseti\VassetiStatus());
                //$tools->append(new \App\Admin\Extensions\Tools\Vasseti\VassetiPublished());
                // $tools->append(new \App\Admin\Extensions\Tools\Vasseti\VassetiAsyncResult());
                // 2017-11-22 add 清除缓存按钮
                // // entity.asset.video.vassetis.clear_cache
                // if (Admin::user()->can('entity.asset.video.vassetis.clear_cache')) {
                //     $tools->append('<a href=' . route('entity.asset.video.vassetis.clear_cache') . ' class="btn btn-sm btn-warning pull-right" style="margin-right: 10px"><i class="fa fa-ban"></i> 清除缓存</a>');
                // }

                $url =  route('entity.assets.assets.model',['sp_no' => '','config_file_select'=>'']);
                $tools->append('<a href=' .$url. ' class="btn btn-sm btn-warning pull-right" title="导入数据"><i class="fa fa-ban"></i>导入数据</a>');


                // 批量按钮
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('entity.asset.video.vassetis.batch_destroy')) {
                        $batch->disableDelete();
                    }
                    // 批量上线按钮
                    // if (Admin::user()->can('entity.asset.video.vassetis.up')) {
                    //     $batch->add('上线', new \App\Admin\Extensions\Tools\Vasseti\ReleaseVasseti('up'));
                    // }
                    // // 批量下线按钮
                    // if (Admin::user()->can('entity.asset.video.vassetis.down')) {
                    //     $batch->add('下线', new \App\Admin\Extensions\Tools\Vasseti\ReleaseVasseti('down'));
                    // }

                    //批量打标签
                    $batch->add('打标签', new \App\Admin\Extensions\Tools\contentTag('vasseti'));

                    //批量导入栏目
                    $batch->add('导入栏目', new \App\Admin\Extensions\Tools\contentColumn('1'));
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('vasseti_no', '编号')->editable();
            $grid->column('name', '名称')->editable();
            $grid->column('vasseti_type', '剧集类型')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-green">单集</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-green">分集总集</span>';
                        break;
                }
            })->sortable();
            $grid->column('title', '标题')->editable();
            // $grid->column('subtitle', '副标题')->sortable();
            $grid->column('score', '评分')->editable()->label('default');
            $grid->column('season', '第几季')->editable();
            $grid->column('serials', '集数')->editable();
            $grid->column('upto', '更新到')->editable();
            $grid->column('vcat.name', '归类')->label('info');
            $grid->vcattags('分类')->pluck('name')->label();
            $grid->tags('标签')->pluck('name')->label('primary');
            $grid->vyears('年代')->pluck('name')->label('default');
            $grid->vareas('地区')->pluck('name')->label('info');
            $grid->vlangs('语言')->pluck('name')->label();
            $grid->column('firstdate', '首播日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            // $grid->vifiles('文件资源地址')->pluck('name')->label();
            // $grid->vposteris('图片')->pluck('name')->label();
            // $grid->column('short_desc', '简介')->sortable();
            // $grid->column('long_desc', '详情')->sortable();
            // $grid->sps('服务商(SP)')->pluck('name')->label();
            // $grid->cps('内容商(CP)')->pluck('name')->label();
            // $grid->directors('导演')->pluck('name')->label();
            // $grid->actors('演员')->pluck('name')->label();
            $grid->column('charge_type', '收费类型')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-green">免费</span>';
                        break;

                    case 1:
                        return '<span class="badge bg-red">收费</span>';
                        break;
                }
            });
            $grid->column('listorder', '排序')->sortable()->editable();
            $grid->column('online_at', '上线日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            $grid->column('offline_at', '下线日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();

            $grid->column('moderate_status', '编辑状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();

            $grid->column('online_status', '上线状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();
            $grid->column('publish_status', '发布状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();
            /**
             * 过滤
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();

                //评分
                $filter->between('score', '评分');

                // 归类
                $tempVcats = Vcat::pluck('name', 'id');
                $filter->equal('vcat_id', '归类')->select($tempVcats);

                // 语言
                $tempVlangs = Vlang::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('vlangs', function ($query) use ($input) {
                        $query->where('vlang_id', '=', "{$input}");
                    });

                }, '语言')->select($tempVlangs);

                // 地区
                $tempVareas = Varea::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('vareas', function ($query) use ($input) {
                        $query->where('varea_id', '=', "{$input}");
                    });

                }, '地区')->select($tempVareas);

                // 服务商(SP)
                $tempSps = Sp::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('sps', function ($query) use ($input) {
                        $query->where('sp_id', '=', "{$input}");
                    });

                }, '服务商')->select($tempSps);

                // 内容商(CP)
                $tempCps = Cp::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('cps', function ($query) use ($input) {
                        $query->where('cp_id', '=', "{$input}");
                    });

                }, '内容商')->select($tempCps);

                // 编号
                $filter->like('vasseti_no', '编号');

                // 标题
                $filter->like('title', '标题');

                // 分类
                $tempVcattags = Vcattag::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('vcattags', function ($query) use ($input) {
                        $query->where('vcattag_id', 'like', "{$input}");
                    });
                }, '分类')->select($tempVcattags);

                // 演员
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('actors', function ($query) use ($input) {
                        $query->where('actors.name', 'like', "%{$input}%");
                    });
                }, '演员');

                // 导演
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('directors', function ($query) use ($input) {
                        $query->where('directors.name', 'like', "%{$input}%");
                    });
                }, '导演');

                // 首播时间
                $filter->between('firstdate', '首播时间')->datetime();
                // 上线时间
                $filter->between('online_at', '上线时间')->datetime();
                // 下线时间
                $filter->between('offline_at', '下线时间')->datetime();

            });
        });
    }

    protected function editor_grid(Request $request)
    {
        return Admin::grid(Vasseti::class, function (Grid $grid) use ($request) {

            // 状态过滤
            // Publication::statusFilter($request->input('status'), $request->input('published'), $grid);
            $grid->model()->where('moderate_status', '!=', 1);

            // 表格中的按钮
            $grid->actions(function ($actions) {

                $id                  = $actions->getKey();
                $url = route('entity.asset.video.vassetis.vasseti_details', ['vasseti_id' => $id]);
                $actions->prepend('<a href ="' . $url . '" title="剧集详情"><i class="fa fa-list"></i></a>');

                // 编辑按钮
                if (Admin::user()->cannot('entity.asset.video.vassetis.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                //if (Admin::user()->cannot('entity.asset.video.vassetis.destroy')) {
                    $actions->disableDelete();
                //}

                // 提交审核申请
                if ( Admin::user()->can('content_audit.content_audits.create.moderate')) {
                    $url      = route('entity.content_audit.content_audits.create.moderate');
                    $function = "upAndDownByOne('$url', 'post', {content_id: $id, content_model: 'vasseti',audit_type: 'moderate', _token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="提交媒资审核申请"><i class="fa fa-eye"></i></a>');
                }

            });

            //添加按钮
            //if (Admin::user()->cannot('entity.asset.video.vassetis.create')) {
                $grid->disableCreation();
            //}

            //导出按钮
            //if (Admin::user()->cannot('entity.asset.video.vassetis.export')) {
                $grid->disableExport();
            //}

            // 批量操作
            $grid->tools(function ($tools) {
                // 批量按钮
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('vasseti_no', '编号')->editable();
            $grid->column('name', '名称')->editable();
            $grid->column('vasseti_type', '剧集类型')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-green">单集</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-green">分集总集</span>';
                        break;
                }
            })->sortable();
            $grid->column('title', '标题')->editable();
            // $grid->column('subtitle', '副标题')->sortable();
            $grid->column('score', '评分')->editable()->label('default');
            $grid->column('season', '第几季')->editable();
            $grid->column('serials', '集数')->editable();
            $grid->column('upto', '更新到')->editable();
            $grid->column('vcat.name', '归类')->label('info');
            $grid->vcattags('分类')->pluck('name')->label();
            $grid->tags('标签')->pluck('name')->label('primary');
            $grid->vyears('年代')->pluck('name')->label('default');
            $grid->vareas('地区')->pluck('name')->label('info');
            $grid->vlangs('语言')->pluck('name')->label();
            $grid->column('firstdate', '首播日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            // $grid->vifiles('文件资源地址')->pluck('name')->label();
            // $grid->vposteris('图片')->pluck('name')->label();
            // $grid->column('short_desc', '简介')->sortable();
            // $grid->column('long_desc', '详情')->sortable();
            // $grid->sps('服务商(SP)')->pluck('name')->label();
            // $grid->cps('内容商(CP)')->pluck('name')->label();
            // $grid->directors('导演')->pluck('name')->label();
            // $grid->actors('演员')->pluck('name')->label();
            $grid->column('charge_type', '收费类型')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-green">免费</span>';
                        break;

                    case 1:
                        return '<span class="badge bg-red">收费</span>';
                        break;
                }
            });
            $grid->column('listorder', '排序')->sortable()->editable();
            // $grid->column('online_at', '上线日期')->display(function ($val) {
            //     if ($val) {
            //         return date('Y-m-d', strtotime($val));
            //     }
            //     return '';
            // })->sortable();
            // $grid->column('offline_at', '下线日期')->display(function ($val) {
            //     if ($val) {
            //         return date('Y-m-d', strtotime($val));
            //     }
            //     return '';
            // })->sortable();
            //
            // $grid->column('online_status', '上线状态')->display(function ($val) {
            //     switch ($val) {
            //         case 0:
            //             return '<span class="badge bg-red">下线</span>';
            //             break;
            //         case 1:
            //             return '<span class="badge bg-green">上线</span>';
            //             break;
            //         default:
            //             return '未知';
            //     }
            // })->sortable();
            $grid->column('moderate_status', '编辑审核')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();

            /**
             * 过滤
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();

                //评分
                $filter->between('score', '评分');

                // 归类
                $tempVcats = Vcat::pluck('name', 'id');
                $filter->equal('vcat_id', '归类')->select($tempVcats);

                // 语言
                $tempVlangs = Vlang::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('vlangs', function ($query) use ($input) {
                        $query->where('vlang_id', '=', "{$input}");
                    });

                }, '语言')->select($tempVlangs);

                // 地区
                $tempVareas = Varea::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('vareas', function ($query) use ($input) {
                        $query->where('varea_id', '=', "{$input}");
                    });

                }, '地区')->select($tempVareas);

                // 服务商(SP)
                $tempSps = Sp::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('sps', function ($query) use ($input) {
                        $query->where('sp_id', '=', "{$input}");
                    });

                }, '服务商')->select($tempSps);

                // 内容商(CP)
                $tempCps = Cp::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('cps', function ($query) use ($input) {
                        $query->where('cp_id', '=', "{$input}");
                    });

                }, '内容商')->select($tempCps);

                // 编号
                $filter->like('vasseti_no', '编号');

                // 标题
                $filter->like('title', '标题');

                // 分类
                $tempVcattags = Vcattag::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('vcattags', function ($query) use ($input) {
                        $query->where('vcattag_id', 'like', "{$input}");
                    });
                }, '分类')->select($tempVcattags);

                // 演员
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('actors', function ($query) use ($input) {
                        $query->where('actors.name', 'like', "%{$input}%");
                    });
                }, '演员');

                // 导演
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('directors', function ($query) use ($input) {
                        $query->where('directors.name', 'like', "%{$input}%");
                    });
                }, '导演');

                // 首播时间
                $filter->between('firstdate', '首播时间')->datetime();

            });
        });
    }


    protected function online_grid(Request $request)
    {
        return Admin::grid(Vasseti::class, function (Grid $grid) use ($request) {

            // 状态过滤
            // Publication::statusFilter($request->input('status'), $request->input('published'), $grid);
            $grid->model()->where('moderate_status', '=', 3)->where('online_status', '!=', 1);

            // 表格中的按钮
            $grid->actions(function ($actions) {

                $id                  = $actions->getKey();
                $url = route('entity.asset.video.vassetis.vasseti_details', ['vasseti_id' => $id]);
                $actions->prepend('<a href ="' . $url . '" title="剧集详情"><i class="fa fa-list"></i></a>');

                // 编辑按钮
                if (Admin::user()->cannot('entity.asset.video.vassetis.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                //if (Admin::user()->cannot('entity.asset.video.vassetis.destroy')) {
                $actions->disableDelete();
                //}

                // 提交上线审核申请
                if ( Admin::user()->can('content_audit.content_audits.create.online')) {
                    $url      = route('entity.content_audit.content_audits.create.online');
                    $function = "upAndDownByOne('$url', 'post', {content_id: $id, content_model: 'vasseti',audit_type: 'online', _token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="提交上线申请"><i class="fa fa-eye"></i></a>');
                }

            });

            //添加按钮
            //if (Admin::user()->cannot('entity.asset.video.vassetis.create')) {
            $grid->disableCreation();
            //}

            //导出按钮
            //if (Admin::user()->cannot('entity.asset.video.vassetis.export')) {
            $grid->disableExport();
            //}

            // 批量操作
            $grid->tools(function ($tools) {
                // 批量按钮
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('vasseti_no', '编号')->editable();
            $grid->column('name', '名称')->editable();
            $grid->column('vasseti_type', '剧集类型')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-green">单集</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-green">分集总集</span>';
                        break;
                }
            })->sortable();
            $grid->column('title', '标题')->editable();
            // $grid->column('subtitle', '副标题')->sortable();
            $grid->column('score', '评分')->editable()->label('default');
            $grid->column('season', '第几季')->editable();
            $grid->column('serials', '集数')->editable();
            $grid->column('upto', '更新到')->editable();
            $grid->column('vcat.name', '归类')->label('info');
            $grid->vcattags('分类')->pluck('name')->label();
            $grid->tags('标签')->pluck('name')->label('primary');
            $grid->vyears('年代')->pluck('name')->label('default');
            $grid->vareas('地区')->pluck('name')->label('info');
            $grid->vlangs('语言')->pluck('name')->label();
            $grid->column('firstdate', '首播日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            // $grid->vifiles('文件资源地址')->pluck('name')->label();
            // $grid->vposteris('图片')->pluck('name')->label();
            // $grid->column('short_desc', '简介')->sortable();
            // $grid->column('long_desc', '详情')->sortable();
            // $grid->sps('服务商(SP)')->pluck('name')->label();
            // $grid->cps('内容商(CP)')->pluck('name')->label();
            // $grid->directors('导演')->pluck('name')->label();
            // $grid->actors('演员')->pluck('name')->label();
            $grid->column('charge_type', '收费类型')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-green">免费</span>';
                        break;

                    case 1:
                        return '<span class="badge bg-red">收费</span>';
                        break;
                }
            });
            $grid->column('listorder', '排序')->sortable()->editable();

            $grid->column('online_status', '上线审核')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();

            /**
             * 过滤
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();

                //评分
                $filter->between('score', '评分');

                // 归类
                $tempVcats = Vcat::pluck('name', 'id');
                $filter->equal('vcat_id', '归类')->select($tempVcats);

                // 语言
                $tempVlangs = Vlang::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('vlangs', function ($query) use ($input) {
                        $query->where('vlang_id', '=', "{$input}");
                    });

                }, '语言')->select($tempVlangs);

                // 地区
                $tempVareas = Varea::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('vareas', function ($query) use ($input) {
                        $query->where('varea_id', '=', "{$input}");
                    });

                }, '地区')->select($tempVareas);

                // 服务商(SP)
                $tempSps = Sp::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('sps', function ($query) use ($input) {
                        $query->where('sp_id', '=', "{$input}");
                    });

                }, '服务商')->select($tempSps);

                // 内容商(CP)
                $tempCps = Cp::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('cps', function ($query) use ($input) {
                        $query->where('cp_id', '=', "{$input}");
                    });

                }, '内容商')->select($tempCps);

                // 编号
                $filter->like('vasseti_no', '编号');

                // 标题
                $filter->like('title', '标题');

                // 分类
                $tempVcattags = Vcattag::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('vcattags', function ($query) use ($input) {
                        $query->where('vcattag_id', 'like', "{$input}");
                    });
                }, '分类')->select($tempVcattags);

                // 演员
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('actors', function ($query) use ($input) {
                        $query->where('actors.name', 'like', "%{$input}%");
                    });
                }, '演员');

                // 导演
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('directors', function ($query) use ($input) {
                        $query->where('directors.name', 'like', "%{$input}%");
                    });
                }, '导演');

                // 首播时间
                $filter->between('firstdate', '首播时间')->datetime();

            });
        });
    }


    protected function publish_grid(Request $request)
    {
        return Admin::grid(Vasseti::class, function (Grid $grid) use ($request) {

            // 状态过滤
            // Publication::statusFilter($request->input('status'), $request->input('published'), $grid);
            $grid->model()->where('online_status', '=', 3)->where('publish_status', '!=', 1);

            // 表格中的按钮
            $grid->actions(function ($actions) {

                $id                  = $actions->getKey();
                $url = route('entity.asset.video.vassetis.vasseti_details', ['vasseti_id' => $id]);
                $actions->prepend('<a href ="' . $url . '" title="剧集详情"><i class="fa fa-list"></i></a>');

                // 编辑按钮
                if (Admin::user()->cannot('entity.asset.video.vassetis.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                //if (Admin::user()->cannot('entity.asset.video.vassetis.destroy')) {
                $actions->disableDelete();
                //}

                // 提交发布审核申请
                if ( Admin::user()->can('content_audit.content_audits.create.publish')) {
                    $url      = route('entity.content_audit.content_audits.create.publish');
                    $function = "upAndDownByOne('$url', 'post', {content_id: $id, content_model: 'vasseti',audit_type: 'publish', _token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="提交发布申请"><i class="fa fa-eye"></i></a>');
                }

            });

            //添加按钮
            //if (Admin::user()->cannot('entity.asset.video.vassetis.create')) {
            $grid->disableCreation();
            //}

            //导出按钮
            //if (Admin::user()->cannot('entity.asset.video.vassetis.export')) {
            $grid->disableExport();
            //}

            // 批量操作
            $grid->tools(function ($tools) {
                // 批量按钮
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('vasseti_no', '编号')->editable();
            $grid->column('name', '名称')->editable();
            $grid->column('vasseti_type', '剧集类型')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-green">单集</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-green">分集总集</span>';
                        break;
                }
            })->sortable();
            $grid->column('title', '标题')->editable();
            // $grid->column('subtitle', '副标题')->sortable();
            $grid->column('score', '评分')->editable()->label('default');
            $grid->column('season', '第几季')->editable();
            $grid->column('serials', '集数')->editable();
            $grid->column('upto', '更新到')->editable();
            $grid->column('vcat.name', '归类')->label('info');
            $grid->vcattags('分类')->pluck('name')->label();
            $grid->tags('标签')->pluck('name')->label('primary');
            $grid->vyears('年代')->pluck('name')->label('default');
            $grid->vareas('地区')->pluck('name')->label('info');
            $grid->vlangs('语言')->pluck('name')->label();
            $grid->column('firstdate', '首播日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            // $grid->vifiles('文件资源地址')->pluck('name')->label();
            // $grid->vposteris('图片')->pluck('name')->label();
            // $grid->column('short_desc', '简介')->sortable();
            // $grid->column('long_desc', '详情')->sortable();
            // $grid->sps('服务商(SP)')->pluck('name')->label();
            // $grid->cps('内容商(CP)')->pluck('name')->label();
            // $grid->directors('导演')->pluck('name')->label();
            // $grid->actors('演员')->pluck('name')->label();
            $grid->column('charge_type', '收费类型')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-green">免费</span>';
                        break;

                    case 1:
                        return '<span class="badge bg-red">收费</span>';
                        break;
                }
            });
            $grid->column('listorder', '排序')->sortable()->editable();

            $grid->column('publish_status', '发布审核')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();

            /**
             * 过滤
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();

                //评分
                $filter->between('score', '评分');

                // 归类
                $tempVcats = Vcat::pluck('name', 'id');
                $filter->equal('vcat_id', '归类')->select($tempVcats);

                // 语言
                $tempVlangs = Vlang::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('vlangs', function ($query) use ($input) {
                        $query->where('vlang_id', '=', "{$input}");
                    });

                }, '语言')->select($tempVlangs);

                // 地区
                $tempVareas = Varea::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('vareas', function ($query) use ($input) {
                        $query->where('varea_id', '=', "{$input}");
                    });

                }, '地区')->select($tempVareas);

                // 服务商(SP)
                $tempSps = Sp::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('sps', function ($query) use ($input) {
                        $query->where('sp_id', '=', "{$input}");
                    });

                }, '服务商')->select($tempSps);

                // 内容商(CP)
                $tempCps = Cp::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('cps', function ($query) use ($input) {
                        $query->where('cp_id', '=', "{$input}");
                    });

                }, '内容商')->select($tempCps);

                // 编号
                $filter->like('vasseti_no', '编号');

                // 标题
                $filter->like('title', '标题');

                // 分类
                $tempVcattags = Vcattag::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('vcattags', function ($query) use ($input) {
                        $query->where('vcattag_id', 'like', "{$input}");
                    });
                }, '分类')->select($tempVcattags);

                // 演员
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('actors', function ($query) use ($input) {
                        $query->where('actors.name', 'like', "%{$input}%");
                    });
                }, '演员');

                // 导演
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('directors', function ($query) use ($input) {
                        $query->where('directors.name', 'like', "%{$input}%");
                    });
                }, '导演');

                // 首播时间
                $filter->between('firstdate', '首播时间')->datetime();

            });
        });
    }


    protected function offline_grid(Request $request)
    {
        return Admin::grid(Vasseti::class, function (Grid $grid) use ($request) {

            // 状态过滤
            // Publication::statusFilter($request->input('status'), $request->input('published'), $grid);
            $grid->model()->where('online_status', '=', 3);

            // 表格中的按钮
            $grid->actions(function ($actions) {

                $id                  = $actions->getKey();
                $url = route('entity.asset.video.vassetis.vasseti_details', ['vasseti_id' => $id]);
                $actions->prepend('<a href ="' . $url . '" title="剧集详情"><i class="fa fa-list"></i></a>');

                // 编辑按钮
                if (Admin::user()->cannot('entity.asset.video.vassetis.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                //if (Admin::user()->cannot('entity.asset.video.vassetis.destroy')) {
                $actions->disableDelete();
                //}


                // 提交下线审核申请
                if ( Admin::user()->can('content_audit.content_audits.create.offline')) {
                    $url      = route('entity.content_audit.content_audits.create.offline');
                    $function = "upAndDownByOne('$url', 'post', {content_id: $id, content_model: 'vasseti',audit_type: 'offline', _token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="提交下线申请"><i class="fa fa-eye"></i></a>');
                }

            });

            //添加按钮
            //if (Admin::user()->cannot('entity.asset.video.vassetis.create')) {
            $grid->disableCreation();
            //}

            //导出按钮
            //if (Admin::user()->cannot('entity.asset.video.vassetis.export')) {
            $grid->disableExport();
            //}

            // 批量操作
            $grid->tools(function ($tools) {
                // 批量按钮
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('vasseti_no', '编号')->editable();
            $grid->column('name', '名称')->editable();
            $grid->column('vasseti_type', '剧集类型')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-green">单集</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-green">分集总集</span>';
                        break;
                }
            })->sortable();
            $grid->column('title', '标题')->editable();
            // $grid->column('subtitle', '副标题')->sortable();
            $grid->column('score', '评分')->editable()->label('default');
            $grid->column('season', '第几季')->editable();
            $grid->column('serials', '集数')->editable();
            $grid->column('upto', '更新到')->editable();
            $grid->column('vcat.name', '归类')->label('info');
            $grid->vcattags('分类')->pluck('name')->label();
            $grid->tags('标签')->pluck('name')->label('primary');
            $grid->vyears('年代')->pluck('name')->label('default');
            $grid->vareas('地区')->pluck('name')->label('info');
            $grid->vlangs('语言')->pluck('name')->label();
            $grid->column('firstdate', '首播日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            // $grid->vifiles('文件资源地址')->pluck('name')->label();
            // $grid->vposteris('图片')->pluck('name')->label();
            // $grid->column('short_desc', '简介')->sortable();
            // $grid->column('long_desc', '详情')->sortable();
            // $grid->sps('服务商(SP)')->pluck('name')->label();
            // $grid->cps('内容商(CP)')->pluck('name')->label();
            // $grid->directors('导演')->pluck('name')->label();
            // $grid->actors('演员')->pluck('name')->label();
            $grid->column('charge_type', '收费类型')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-green">免费</span>';
                        break;

                    case 1:
                        return '<span class="badge bg-red">收费</span>';
                        break;
                }
            });
            $grid->column('listorder', '排序')->sortable()->editable();

            $grid->column('id', '下线审核')->display(function ($val) {
                $status = content_audit::audit_status($val,'vasseti','offline');
                switch ($status) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();

            /**
             * 过滤
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();

                //评分
                $filter->between('score', '评分');

                // 归类
                $tempVcats = Vcat::pluck('name', 'id');
                $filter->equal('vcat_id', '归类')->select($tempVcats);

                // 语言
                $tempVlangs = Vlang::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('vlangs', function ($query) use ($input) {
                        $query->where('vlang_id', '=', "{$input}");
                    });

                }, '语言')->select($tempVlangs);

                // 地区
                $tempVareas = Varea::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('vareas', function ($query) use ($input) {
                        $query->where('varea_id', '=', "{$input}");
                    });

                }, '地区')->select($tempVareas);

                // 服务商(SP)
                $tempSps = Sp::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('sps', function ($query) use ($input) {
                        $query->where('sp_id', '=', "{$input}");
                    });

                }, '服务商')->select($tempSps);

                // 内容商(CP)
                $tempCps = Cp::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('cps', function ($query) use ($input) {
                        $query->where('cp_id', '=', "{$input}");
                    });

                }, '内容商')->select($tempCps);

                // 编号
                $filter->like('vasseti_no', '编号');

                // 标题
                $filter->like('title', '标题');

                // 分类
                $tempVcattags = Vcattag::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('vcattags', function ($query) use ($input) {
                        $query->where('vcattag_id', 'like', "{$input}");
                    });
                }, '分类')->select($tempVcattags);

                // 演员
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('actors', function ($query) use ($input) {
                        $query->where('actors.name', 'like', "%{$input}%");
                    });
                }, '演员');

                // 导演
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('directors', function ($query) use ($input) {
                        $query->where('directors.name', 'like', "%{$input}%");
                    });
                }, '导演');

                // 首播时间
                $filter->between('firstdate', '首播时间')->datetime();

            });
        });
    }


    /**
     * 批量导入媒资-视图
     * @param Request $request
     */
    public function batchImportView()
    {
        return Admin::content(function (Content $content) {
            $content->header(__('entity.asset.video.vassetis.batch_import_header'));
            $content->description(__('entity.asset.video.vassetis.batch_import_description'));

            $box = new Box('模板说明', '<p><b>编号</b>(必填), <b>分集编号</b>(非必填, 分集时才填写), <b>CP/SP</b>(必填), <b>剧集名称</b>(必填), <b>分集名称</b>(非必填, 分集时才填写), <b>集数</b>(非必填, 剧集时代表总集数, 分集时代表第几集), <b>第几季</b>(非必填), <b>产地</b>(必填, 多个媒资地区之间使用<b>&</b>连接), <b>分类</b>(必填, 多个分类之间使用<b>&</b>连接), <b>归类</b>(必填), <b>语言</b>(非必填, 多个分类之间使用<b>&</b>连接), <b>时长(分钟)</b>(非必填, 整数, 默认给60), <b>导演</b>(必填, 多个导演之间使用<b>&</b>连接), <b>导演地区</b>(必填, 多个导演地区之间使用<b>&</b>连接, 导演地区应该和导演的个数一致), <b>主演</b>(必填, 多个主演之间使用<b>&</b>连接), <b>简介</b>(必填), <b>详情</b>(非必填), <b>评分</b>(非必填, 默认给10分), <b>图片文件目录</b>(非必填), <b>视频文件目录</b>(非必填), <b>上映时间</b>(必填, 精确到天, 格式:2017/8/23或2017-8-23), <b>年代</b>(非必填)。点击 "下载模板" 按钮, 进行数据格式的下载!<a href="/upload/batch_import_template/vasseti_sample.xlsx" class="btn btn-warning" target="_blank"><i class="fa fa-download"></i>下载模板</a></p></p>');
            $content->row($box->style('primary'));

            $content->body($this->batchImportForm());
        });
    }

    /**
     * 批量的导入媒资的form
     */
    protected function batchImportForm()
    {
        // Admin::script('tian();');

        // 文件
        return Admin::form(Vasseti::class, function (Form $form) {
            // 设置表单提交的action
            $form->setAction(route('entity.asset.video.vassetis.batch_import'));
            // 编辑界面的按钮
            $form->tools(function (Form\Tools $tools) {
                // 去掉返回按钮
                // $tools->disableBackButton();
                // 去掉跳转列表按钮
                $tools->disableListButton();
                // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
                // $tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
            });

            Admin::script('batchImportVasseti();');

            $form->file('file', '文件');
        });
    }

    /**
     * 批量导入媒资
     * [batchImport description]
     * @return [type] [description]
     */
    public function batchImport(Request $request)
    {
        // 定义校验, 没有移到request
        $validator = Validator::make($request->all(), [
            'file' => 'required', // |mimes:xls,csv,xlsx
        ], [
            'required' => ':attribute 未上传',
            // 'mimes' => '文件格式只能为 :attribute',
        ], [
            'file' => '文件',
        ]);
        // 校验
        if ($validator->fails()) {
            // json返回
            return response()->json(['status' => 'error', 'content' => '文件不能为空!']);

            // return back()->withErrors($validator)->withInput();
        }

        // 上传文件:
        $file = $request->file('file');

        // 文件是否上传成功
        if ($file->isValid()) {
            // 允许上传的文件格式
            $allowed_extensions = ["xls", "xlsx", "csv"];
            // 上传文件的后缀, 扩展名
            $entension = $file->getClientOriginalExtension();
            if ($entension && !in_array($entension, $allowed_extensions)) {
                // json返回
                return response()->json(['status' => 'error', 'content' => '文件格式只能为xls, xlsx, csv!']);

                // Flash::error('文件格式只能为xls, xlsx, csv!');
                // // 关联持久用户提交的信息
                // return back()->withInput();
            }
            //获取文件尺寸
            $size = $file->getSize();
            // 文件最大限制, 现在是10M
            $file_max_size = config('custom.base.file_max_size');
            // $size = round($file->getSize() / 1024 / 1024);
            if ($size > $file_max_size) {
                // json返回
                return response()->json(['status' => 'error', 'content' => '文件最大只能10M!']);

                // Flash::error('文件最大只能10M!');
                // return back()->withInput(); //关联持久用户提交的信息
            }

            $originalName = $file->getClientOriginalName(); // 文件原名
            $type         = $file->getClientMimeType(); // image/jpeg
            $realPath     = $file->getRealPath(); // 临时文件的绝对路径
            $fileName     = date('YmdHis') . '-' . uniqid();
            $newName      = $fileName . '.' . $entension;
            // 文件上传的根路径
            $rootDir     = config('filesystems.disks.custom.root');
            $path        = $file->move($rootDir . '/import_vasset', $newName);
            $cretae_path = $rootDir . '/import_vasset/' . $newName;
            // 保存日志时文件路径
            $file_url = '/import_vasset/' . $newName;

            // 通过excel先读取一下总行数, 效率有点低, 因为先将所有的excel数据读入到内存了
            $count = 0;
            Excel::load($cretae_path, function ($reader) use (&$count) {
                $reader = $reader->getSheet(0);
                //获取表中的数据
                $data  = $reader->toArray();
                $num   = count($data);
                $count = $num - 1;
            });

            // 创建一条记录
            $batchImportVassetiHistory                  = new BatchImportVassetiHistory;
            $batchImportVassetiHistory->batch_no        = date('YmdHis');
            $batchImportVassetiHistory->task_no         = date('YmdHis') . uniqid();
            $batchImportVassetiHistory->done_count      = 0;
            $batchImportVassetiHistory->file_url        = $file_url;
            $batchImportVassetiHistory->success_count   = 0;
            $batchImportVassetiHistory->diversity_count = 0;
            $batchImportVassetiHistory->error_count     = 0;
            $batchImportVassetiHistory->count           = $count;
            $batchImportVassetiHistory->content         = "开始";
            $batchImportVassetiHistory->consuming_time  = 0;
            $batchImportVassetiHistory->used_memory     = 0;
            $batchImportVassetiHistory->user_id         = Admin::user()->id;
            $batchImportVassetiHistory->save();

            // 触发队列
            dispatch(new ImportVassetiJob($cretae_path, $batchImportVassetiHistory));

            // json返回
            return response()->json(['status' => 'success', 'content' => $batchImportVassetiHistory->task_no]);

            // return back()->withInput();
        } else {
            // json返回
            return response()->json(['status' => 'error', 'content' => '文件上传失败!']);

            // Flash::error('文件上传失败');
            // return back()->withInput(); //关联持久用户提交的信息
        }
    }

    /**
     * 批量导入媒资进度
     * [queryProgress description]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function bacthImportProgress(Request $request)
    {
        $taskNo = $request->input('task_no');
        $data   = BatchImportVassetiHistory::where('task_no', $taskNo)->first();
        // 记录数为0[异常]
        if ($data->count === 0) {
            return response()->json(['content' => '记录数为0!', 'status' => 'success']);
        }
        // 完成数为0
        if ($data->done_count === 0) {
            return response()->json(['content' => '0%', 'status' => 'progress']);
        }
        // 完成的时候
        if ($data->count === $data->done_count) {
            return response()->json(['content' => $data->content, 'status' => 'success']);
        }
        // 异常
        if ($data->count < $data->done_count) {
            return response()->json(['content' => '任务异常, 完成数大于总数！', 'status' => 'success']);
        }
        return response()->json(['content' => ceil($data->done_count * 100 / $data->count) . '%', 'status' => 'progress']);
    }



    /**
     * 全部上线功能
     */
    public function allUp()
    {
        if (Admin::user()->cannot('entity.asset.video.vassetis.all_up')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Vasseti::where(['online_status' => 0, 'publish_down_status' => 1])->count();
        $result = Publication::getTotalNum(new Vasseti(), [
            [['online_status' => 0], 'ID为以下媒资已经上线: '],
            [['publish_down_status' => 1], 'ID为以下媒资还未下线发布: '],
        ], '媒资上线');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data   = ['task_type' => '剧集上线', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new VassetiJob(['dispatch', 'up'], '', $taskid));
        $content = $content ? $content : '上线成功!';
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 全部下线功能
     */
    public function allDown()
    {
        if (Admin::user()->cannot('entity.asset.video.vassetis.all_down')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Vasseti::where(['online_status' => 1])->count();
        $result = Publication::getTotalNum(new Vasseti(), [
            [['online_status' => 1], 'ID为以下媒资还没上线'],
        ], '媒资下线');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data   = ['task_type' => '剧集下线', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new VassetiJob(['dispatch', 'down'], '', $taskid));
        $content = $content ? $content : '下线成功!';
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 发布功能,由于是全部发布,整个操作放入队列
     */
    public static function publish(Request $request)
    {
        if (Admin::user()->cannot('entity.asset.video.vassetis.publish')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        $result = Publication::getTotalNum(new Vasseti(), [
            [['online_status' => 1], 'ID为以下媒资还未上线: '],
            [['publish_status' => 0], 'ID为以下媒资已经上线发布: '],
        ], '媒资发布');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data = ['task_type' => '剧集发布', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        // 任务表插入一条记录
        $taskid = Publication::insertTasks($data);
        dispatch(new VassetiJob(['dispatch', 'publish'], '', $taskid));
        $content = $content ? $content : '发布成功!';
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 下线发布功能
     */
    public function publishDown(Request $request)
    {
        if (Admin::user()->cannot('entity.asset.video.vassetis.publish_down')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Vasseti::where(['online_status' => 0, 'publish_down_status' => 0])->count();
        $result = Publication::getTotalNum(new Vasseti(), [
            [['online_status' => 0], 'ID为以下媒资还未下线: '],
            [['publish_down_status' => 0], 'ID为以下媒资已经下线发布: '],
        ], '媒资下线发布');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data = ['task_type' => '剧集下线发布', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        // 任务表插入一条记录
        $taskid = Publication::insertTasks($data);
        dispatch(new VassetiJob(['dispatch', 'publishDown'], '', $taskid));
        $content = $content ? $content : '下线发布成功!';
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 单个,批量上下线功能,单个,单个发布功能
     */
    public function batchModerate(Request $request)
    {
        $user_id = Admin::user()->id;
        switch ($request->action) {
            // 上线
            case 'up':
                if (Admin::user()->cannot('entity.asset.video.vassetis.up')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // 过滤ids
                $result = Publication::myfilter(new Vasseti(), $request->ids, [
                    [['online_status' => 0], 'ID为以下媒资已经上线: '],
                    [['publish_down_status' => 1], 'ID为以下媒资还未下线发布: '],
                ], '媒资上线');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                $result = Publication::updateMany(new Vasseti(), $ids, [
                    'online_status'       => 1,
                    'publish_down_status' => 0,
                    'user_id'             => $user_id,
                    'online_at'           => date('Y-m-d H:i:s'),
                ]);
                // 如果所有的ids都能上线,显示上线操作成功,否则显示失败的ids
                $content = $content ? $content : '上线成功!';
                // 判断数据库状态是否更新成功
                $content = $result ? $content : '上线失败';
                return response()->json(['status' => 'success', 'content' => $content]);
            // 发布
            case 'publish':
                if (Admin::user()->cannot('entity.asset.video.vassetis.publish')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                $result = Publication::myfilter(new Vasseti(), $request->ids, [
                    [['online_status' => 1], 'ID为以下媒资还未上线: '],
                    [['publish_status' => 0], 'ID为以下媒资已经上线发布: '],
                    [['async_result' => 1], 'ID为以下媒资还未注入: '],
                ], '媒资发布');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                // 如果是批量放入队列中处理
                if (count($ids) > 1) {
                    $data   = ['task_type' => '剧集发布', 'user_id' => $user_id, 'total_num' => count($ids)];
                    $taskid = Publication::insertTasks($data);
                    dispatch(new VassetiJob(['publish'], $ids, $taskid));
                    $url = route('entity.asset.video.vassetis.progress');
                    return response()->json(['status' => 'success', 'content' => $content, 'taskid' => $taskid, 'url' => $url]);
                }
                // 如果是单条数据发布
                $vassetis = Vasseti::with(['directors', 'actors', 'vposteris', 'vcattags', 'vifiles'])
                    ->whereIn('id', $ids)->get();
                $vassetis_vcattags     = VassetiVcattag::whereIn('vasseti_id', $ids)->get();
                $vasseti_datas         = VassetiJob::makeVassetis($vassetis);
                $vasseti_vcattag_datas = VassetiJob::makeVassetiVcattags($vassetis_vcattags);
                $result1               = Publication::insertApi('vassetis', $vasseti_datas);
                $result2               = Publication::insertApi('vasseti_vcattags', $vasseti_vcattag_datas);
                /**
                 * 清除redis中缓存的媒资
                 */
                $templateKey = 'vasseti:';
                foreach ($ids as $key => $value) {
                    $requestKey = $templateKey . $value;
                    // 调用瀚动接口清除缓存的路由'
                    $requestData = [
                        'redis_key' => $requestKey,
                    ];
                    // 请求类型
                    $type = "post";
                    $url  = config('custom.base.cache_host') . "clear_cache"; // http://10.69.42.146/
                    // $url        = "http://10.69.42.146/clear_cache?" . http_build_query($requestData);
                    $interfaceResult = proxy_http_request($type, $url, $requestData);
                }
                $result3 = Publication::updateMany(new Vasseti(), $ids, [
                    'publish_status' => 1,
                    'user_id'        => $user_id,
                ]);
                // 如果所有的ids都能上线,显示上线操作成功,否则显示失败的ids
                $content = $content ? $content : '上线发布成功!';
                // 判断数据库状态是否更新成功
                $content = ($result1 && $result2 && $result3) ? $content : '上线发布失败';
                return response()->json(['status' => 'success', 'content' => $content]);
            // 下线
            case 'down':
                if (Admin::user()->cannot('entity.asset.video.vassetis.down')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                $result = Publication::myfilter(new Vasseti(), $request->ids, [
                    [[['async_result', '<>', 0]], 'ID为以下媒资正在注入'],
                    [['online_status' => 1], 'ID为以下媒资还没上线'],
                ], '媒资下线');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                $result = Publication::updateMany(new Vasseti(), $ids, [
                    'online_status'  => 0,
                    'publish_status' => 0,
                    'user_id'        => $user_id,
                    'offline_at'     => date('Y-m-d H:i:s'),
                ]);
                // 如果所有的ids都能上线,显示上线操作成功,否则显示失败的ids
                $content = $content ? $content : '下线成功!';
                // 判断数据库状态是否更新成功
                $content = $result ? $content : '下线失败';
                return response()->json(['status' => 'success', 'content' => $content]);
            // 下线发布
            case 'publishDown':
                if (Admin::user()->cannot('entity.asset.video.vassetis.publish_one')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                $result = Publication::myfilter(new Vasseti(), $request->ids, [
                    [['online_status' => 0], 'ID为以下媒资还未下线: '],
                    [['publish_down_status' => 0], 'ID为以下媒资已经下线发布: '],
                ], '媒资下线发布');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                /*
                 * 删除接口库中对应的数据
                 * 这里有两种可能的情况
                 * 1.资源还没有上线发布就被下线, 接口库没有还没有这个资源
                 * 2.资源已经上线发布过, 接口库中有这个资源
                 * 所以在删除接口库中的数据时, 需要先判断接口库中是否有对应数据, 有则返回删除操作的结果, 没有则直接返回true
                 */
                $vassetisCount = DB::connection('interface')->table('vassetis')->whereIn('vasseti_id', $ids)->count();
                if ($vassetisCount) {
                    $result1 = Publication::deleteApi('vassetis', 'vasseti_id', $ids);
                } else {
                    $result1 = true;
                }
                $vassetiVcattagsCount = DB::connection('interface')->table('vasseti_vcattags')->whereIn('vasseti_id', $ids)->count();
                if ($vassetiVcattagsCount) {
                    $result2 = Publication::deleteApi('vasseti_vcattags', 'vasseti_id', $ids);
                } else {
                    $result2 = true;
                }
                // 更新状态
                $result3 = Publication::updateMany(new Vasseti(), $ids, [
                    'publish_down_status' => 1,
                    'user_id'             => $user_id,
                ]);
                // 如果所有的ids,显示操作成功,否则显示失败的ids
                $content = $content ? $content : '下线发布成功!';
                // 判断数据库状态是否更新成功
                $content = $result1 && $result2 && $result3 ? $content : '下线发布失败';
                return response()->json(['status' => 'success', 'content' => $content]);
        }
    }

    /**
     * 查询进度
     */
    public function queryProgress(Request $request)
    {
        $taskid = (int) $request->input('taskid');
        return Publication::progress($taskid);
    }

    /**
     * 清除缓存
     */
    public function clearCache(Request $request)
    {

        $requestKey = 'vasseti:*';
        // 调用瀚动接口清除缓存的路由'
        $requestData = [
            'redis_key' => $requestKey,
        ];
        // 请求类型
        $type            = "post";
        $url             = config('custom.base.cache_host') . "clear_cache"; // http://10.69.42.146/
        $interfaceResult = proxy_http_request($type, $url, $requestData);

        Flash::success('清除缓存成功!');
        return redirect(route('entity.asset.video.vassetis.index'));
    }

}
